﻿using System;
using OpenCvSharp;
namespace TemplateMaker
{
    /// <summary>
    /// 模板制作，利用前后景侦查获取目标区域，进而获得模板
    /// </summary>
    public class Maker
    {
        private Mat Mask;
        // todo 进一步扩大模板边界，目前轮廓紧贴边界导致识别模板存在问题故采用手动截取模板临时替代，暂时不推荐使用
        public bool MakeMask(Mat background,Mat image)
        {
  
            Point[][] contours;
            Point[] ponits;
            HierarchyIndex[] hierarchy;
            //todo 图像目标尺寸需要调整
            var dsize = new Size(1008,756);
            var mask = new Mat(dsize,MatType.CV_8UC3);
            var origin = image.Clone();
            var bounding_image = new Mat(dsize, MatType.CV_8U);
            var bounding_detector = new Mat(dsize, MatType.CV_8U);
            
            Cv2.Resize(origin,origin,dsize);
            Cv2.Resize(background,background,dsize);
            Cv2.Resize(image,image,dsize);
            Cv2.CvtColor(background,background,ColorConversionCodes.BGR2GRAY);
            Cv2.CvtColor(image,image,ColorConversionCodes.BGR2GRAY);
            Mat diff_image = new Mat(image.Rows,image.Cols,MatType.CV_8U);
            Cv2.Absdiff(background,image,diff_image);
            Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(5, 5));
            
            Cv2.Canny(diff_image, bounding_detector,3,9,3);
            Cv2.MorphologyEx(bounding_detector, bounding_detector, MorphTypes.Close, element);
            Cv2.FindContours(bounding_detector,out contours,out hierarchy,RetrievalModes.External,ContourApproximationModes.ApproxNone);
            origin.CopyTo(bounding_image,bounding_detector);
            Cv2.DrawContours(mask,contours,0,Scalar.Coral);

            var min_react = Cv2.BoundingRect(contours[0]);
            // Cv2.Rectangle(origin,min_react,Scalar.Aqua);
            Mat result = new Mat(origin, min_react);
            Cv2.ImShow("roi",result);
            Cv2.ImShow("Canny",bounding_detector);
            Cv2.ImShow("bounding",bounding_image);
            Cv2.ImShow("contours",mask);
            Cv2.ImShow("diff",diff_image);
            if(Cv2.WaitKey(0)=='s')
                Cv2.ImWrite("Tempelate.png",result);
            return true;
        }
        
    }
}